#!/bin/sh

InstallDir=/usr/bin

cfile=/etc/vconfig
log_out=$InstallDir/vadsl_logout
nf_tables=nft

#检测是否为ROOT身份
uid=$(id -u)
if [ "$uid" != "0" ]
then
	echo 请以ROOT身份运行
	exit 1
fi

if [ -f $cfile ]
then
	echo 使用配置文件 $cfile
else
	echo 未找到配置文件 $cfile
	exit 1
fi

interface=$(sed -ne '/^#/d; s/\(interface\)\( \)\(.*\)/\3/p' $cfile)
bindip=$(sed -ne '/^#/d; s/\(bindip\)\( \)\(.*\)/\3/p' $cfile)
authserver=$(sed -ne '/^#/d; s/\(authserver\)\( \)\(.*\)/\3/p' $cfile)
account=$(sed -ne '/^#/d; s/\(account\)\( \)\(.*\)/\3/p' $cfile)
threadsnum=$(sed -ne '/^#/d; s/\(threadsnum\)\( \)\(.*\)/\3/p' $cfile)
logfile=$(sed -ne '/^#/d; s/\(logfile\)\( \)\(.*\)/\3/p' $cfile)

[ -z $threadsnum ] || threadsnum=2

#nftables设置
if [ -z $(grep nftablesRulesSet $logfile) ]
then
	echo 未发现相应nftables规则
else
	echo 开始清除nftables设置
	nft flush table vadsl-mangle
	nft delete chain vadsl-mangle output
	nft delete table vadsl-mangle
	echo nftables设置已清除
fi

#结束登录和路由过滤进程
echo 检测登录和路由过滤进程
loginpid=$(grep loginpid $logfile | cut -d':' -f5)
logindpid=$(grep logindpid $logfile | cut -d':' -f5)
[ -z $loginpid ] || [ -z $(ps -eo pid | grep $loginpid) ] || (echo 发现登录进程$loginpid && kill $loginpid)
[ -z $logindpid ] || [ -z $(ps -eo pid | grep $logindpid) ] || (echo 发现后台登录进程$logindpid && kill $logindpid)
echo 登录进程已终止
nfqpid=$(grep nfqpid $logfile | cut -d':' -f5)
nfqdpid=$(grep nfqdpid $logfile | cut -d':' -f5)
[ -z $nfqpid ] || [ -z $(ps -eo pid | grep $nfqpid) ] || (echo 发现路由过滤进程$nfqpid && kill $nfqpid)
[ -z $nfqdpid ] || [ -z $(ps -eo pid | grep $nfqdpid) ] || (echo 发现后台路由过滤进程$nfqdpid && kill $nfqdpid)
echo 路由过滤进程已终止

echo 恢复 $interface MTU设置
ifconfig $interface mtu 1500

echo 发送下线请求
$log_out -b $bindip -s $authserver -a $account 2> $logfile

exit 0
